﻿@using Resource;
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="Cache" content="no-cache">
    @{ await Html.RenderPartialAsync("/Views/Shared/_LayoutScript.cshtml"); }
    @{ await Html.RenderPartialAsync("/Views/Shared/_StyleCss.cshtml"); }

    <script src="/lib/later/later.js?v=@DateTime.Now.Ticks"></script>
    <link href="/css/Yieldboard.css?v=@DateTime.Now.Ticks" rel="stylesheet" />
    <title>Yieldboard</title>
    <style>
        .hover-image {
            display: none;
            position: absolute;
            top: 20px;
            left: 0;
            width: 35vw;
            border: 1px solid #ccc;
            background: #fff;
            z-index: 999;
        }

        .warn-flag:hover .hover-image {
            display: block;
        }

        /*报表放大*/
        #maximizedreport {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            margin: 0;
            z-index: 1000;
            transition: all 0.3s;
            font-size: 1.5em !important;
            background-color: #073758;
        }

        #maximizedreport #board #startdate,
        #maximizedreport #board #enddate {
            font-size: 0.85em !important;
            width: 12.5vw;
        }

        #maximizedreport #board select,
        #maximizedreport #board button {
            font-size: 0.85em !important;
            width: 9vw;
        }

        #maximizedreport #table-container {
            height: 90vh;
            font-size: 0.85em !important;
        }

        #maximizedreport #table-container th {
            font-size: 1.45em !important;
        }
        /*良率图表放大*/
        #maximizedyieldchart {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            margin: 0;
            z-index: 1000;
            transition: all 0.3s;
            font-size: 1.5em !important;
            background-color: #073758;
        }

        #maximizedyieldchart .tab,
        #maximizedyieldchart .tab button {
            height: 7vh;
            font-size: 1.1em !important;
        }

        #maximizedyieldchart .tab button {
            border-bottom: 0.2em solid #ffffff;
        }

        #maximizedyieldchart .tab button.active {
            border-bottom: 0.2em solid #0080cc;
        }

        #maximizedyieldchart #chart1 {
            height: 100vh;
        }

        #maximizedyieldchart .tab #cmb_fail_type,
        #maximizedyieldchart .tab #cmb_type,
        #maximizedyieldchart .tab .search {
            height: 7vh;
            line-height: 7vh;
            font-size: 0.9em !important;
        }

        #maximizedyieldchart .tab #cmb_data_type {
            height: 3.5vh;
            width: 5vw;
            font-size: 0.9em !important;
        }

        #maximizedyieldchart .tab #process_input {
            height: 3.5vh;
            width: 10vw;
            font-size: 0.9em !important;
        }

        #maximizedyieldchart .tab #cmb_failuremode {
            height: 3.5vh;
            width: 10vw;
            font-size: 0.9em !important;
        }

        /*柏拉图放大*/
        #maximizedplato {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            margin: 0;
            z-index: 1000;
            transition: all 0.3s;
            font-size: 1.5em !important;
            background-color: #073758;
        }

        #maximizedplato #chart2 {
            height: 95vh;
            margin-top: 5vh;
        }

        #maximizedplato .title #cmb_plato,
        #maximizedplato .title #cmb_tester {
            height: 7vh;
            font-size: 0.9em !important;
        }

        #maximizedplato .title #cmb_plato_type,
        #maximizedplato .title #cmb_tester_type {
            height: 3.5vh;
            width: 10vw;
            font-size: 0.9em !important;
        }
    </style>
</head>
<body class="fill-parent" style="overflow-y: hidden">
    <div class="main">
        <div class="header">
            <div class="header-left fl">
                <img src="/images/logo.png?v=@DateTime.Now.Ticks" class="scaled-image" draggable="false" oncontextmenu="return false;" ondragstart="return false;" />
            </div>
            <div class="btn">
                <spn>
                    <div id="query">
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Desktop</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" href=@Html.Raw($"https://dashboard.li.lumentuminc.net/API/DesktopApp/Dashboard.exe?v={DateTime.Now.Ticks}") download>@Label.Local</a>
                                <a class="menudropdown" href=@Html.Raw($"https://dashboard.li.lumentuminc.net/API/DesktopApp/Dashboard_lnk.zip?v={DateTime.Now.Ticks}") download>@Label.Shortcut</a>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Data@Label.Datum</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" onclick="ModalShow('TestFailGroup')">@Label.Datum@Label.Maintain</a>
                                <a class="menudropdown" onclick="TestDataExport('TestData')">@Label.Data@Label.Export</a>
                                <a class="menudropdown" onclick="YieldReportExport('YieldReport')">@Label.Report@Label.Export</a>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Language</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" onclick="setLanguageCookie('@Const.CNLANGUAGE')">@Label.Chinese</a>
                                <a class="menudropdown" onclick="setLanguageCookie('@Const.USLANGUAGE')">@Label.English</a>
                            </div>
                        </div>
                        <button class="modalBtn dimension">@Label.Full</button>
                    </div>
                </spn>
            </div>
            <div class="header-center fl">
                <div class="header-title"></div>
                <div class="header-img"></div>
            </div>
            <div class="header-right fl" id="time"></div>
            <div class="header-bottom fl"></div>
        </div>
        <div class="center">
            <div class="center-left fl">
                <div class="left-top rightTop border" id="report_id" ondblclick="maximizedreport()">
                    <div class="title">
                        <span class="warn-flag" style="color:red; position: relative;">ℹ️<img src="../images/lot.png?v=@DateTime.Now.Ticks" class="hover-image" /></span>
                        @Label.Report
                    </div>
                    <div id="board" class="chart">
                        <div class="query">
                            @*<span class="exampleInputProject tle">@Label.Time:</span>*@
                            <input type="datetime-local" id="startdate" name="startdate" placeholder="@Label.Start@Label.Time">
                            <span class="exampleInputProject tle">@Label.To</span>
                            <input type="datetime-local" id="enddate" name="enddate" placeholder="@Label.Start@Label.End">
                            <select id="cmb_area_type" name="AreaType" placeholder="select area">
                                <option value="DG">@Label.DG</option>
                                <option value="AMT">@Label.AMT</option>
                                <option value="NAVA">@Label.NAVA</option>
                            </select>
                            <select id="cmb_prod_type" name="ProdType" placeholder="select prodtype">
                                <option value="ALL">@Label.ALL</option>
                                <option value="Normal">@Label.Fresh</option>
                                <option value="Rework">@Label.Rework</option>
                                <option value="RMA">@Label.RMA</option>
                            </select>
                            <select id="cmb_proj_code">
                                <option value="">@Label.PleaseSelect</option>
                            </select>
                            <select id="cmb_process_code">
                                <option value="">@Label.PleaseSelect</option>
                            </select>
                            <button id="btn_query" class="btn btn-primary  btn-sm col-md-12" type="button" onclick="getdata()">@Label.Query</button>
                        </div>
                        <div id="table-container">
                            <table class="DataSheet" border="1" style="width: 100%; height: 100%;">
                                <thead>
                                    <tr>
                                        <th>Station</th>
                                        <th>Input</th>
                                        <th>Output</th>
                                        <th>PrimeYield</th>
                                        <th>FinalYield</th>
                                        <th>FailureMode</th>
                                        <th>PrimeReject</th>
                                        <th>RetestPass</th>
                                        <th>PrimeRejectRate</th>
                                        <th>FinalRejectRate</th>
                                    </tr>
                                </thead>
                                <tbody id="yield_tbody"></tbody>
                                <tfoot>
                                    <tr>
                                        <th id="sum" colspan="3"></th>
                                        <th id="primeyield"></th>
                                        <th id="finalyield"></th>
                                        <th></th>
                                        <th></th>
                                        <th></th>
                                        <th></th>
                                        <th></th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="center-right fr">
                <div class="right-top rightTop border" id="yield_id" ondblclick="maximizedyieldchart()">
                    <div class="tab">
                        <button class="tablinks active" onclick="OpenTab(event,'tab','chart1',TesterPrimeYieldChartFun)">Tester&nbsp;Prime&nbsp;Yield&nbsp;Chart</button>
                        <button class="tablinks" onclick="OpenTab(event,'tab','chart1',FinalYieldChartFun)">Final&nbsp;Yield&nbsp;Trend&nbsp;Chart</button>
                        <button class="tablinks" onclick="OpenTab(event,'tab','chart1',FailureModeAreaChartFun)">FailureMode&nbsp;Area&nbsp;Chart</button>
                        <div id="cmb_fail_type">
                            <select id="cmb_failuremode" placeholder="select failuremode">
                                <option value="ALL">@Label.ALL</option>
                            </select>
                        </div>
                        <div id="cmb_type">
                            <select id="cmb_data_type">
                                <option value="WEEK">周</option>
                                <option value="DAY">天</option>
                            </select>
                        </div>
                        <div class="search">
                            <input list="process_search" id="process_input" name="search" placeholder="请输入Process...">
                            <datalist id="process_search" class="process_search"></datalist>
                        </div>
                    </div>
                    <div id="chart1" class="chart"></div>
                </div>
                <div class="right-bottom rightTop border" id="plato_id" ondblclick="maximizedplato()">
                    <div class="title">
                        <label>@Html.Raw(Label.Plato)</label>
                        <div id="cmb_tester">
                            <select id="cmb_tester_type">
                                <option value="ALL">@Label.ALL</option>
                            </select>
                        </div>
                        <div id="cmb_plato">
                            <select id="cmb_plato_type">
                                <option value="FinalPlato">FinalPlato</option>
                                <option value="PrimePlato">PrimePlato</option>
                            </select>
                        </div>
                    </div>
                    <div id="chart2" class="chart"></div>
                </div>
            </div>
        </div>
    </div>
    <!-- 模态框 -文件下载上传 -->
    <div class="modal">
        <div class="modal-content family">
            <span class="close" onclick="ModalClose('modal')">×</span>
            <p id="Item" class="modal-title">@Html.Raw(Label.Settings + Label.Output + Label.Target)</p>
            <br>
            <div class="form-flex">
                <label for="projcode">projcode:</label>
                <select id="projcode" name="projcode" placeholder="select projcode"></select>
                <label for="process">process:</label>
                <select id="process" name="process" placeholder="select process"></select>
                <label>
                    <span><label><button type="submit" style="background-color: #49c5ce;" onclick="TestFailGroupExport()"><span><img src="/images/ProcessCapacity/Excel.ico" alt="Excel" class="icon"></span>生成Excel模板</button></label></span>
                    <span id="export"></span>
                </label>
                <span>
                    <label>@Html.Raw(Label.Import + Label.Template):</label>&nbsp;
                    <span><input type="file" id="Template" name="Template" style="width:calc(100% - 0.78rem)" placeholder="Enter your Process"></span>
                </span>
                <label for="message">message:</label>
                <input type="text" id="message" name="message" placeholder="Enter your message">
                <button type="submit" style="font-weight: bold; height:0.5rem;" onclick="UploadExcel()">Submit</button>
            </div>
        </div>
    </div>

    <script type="text/javascript" href="?v=@DateTime.Now.Ticks">
        //模板初始化配置
        $(document).ready(function () {
            var whei = $(window).height();
            $("html").css({ fontSize: whei / 12.5 });
            $(window).resize(function () {
                if ($(".dimension").text() == "@Html.Raw(Label.Full)") {
                    var whei = $(window).height();
                    $("html").css({ fontSize: whei / 12.5 });
                }
                else {
                    var whei = $(window).width();
                    $("html").css({ fontSize: whei / 22 })
                }
                echartsautomatic();
            });

            /*当前时间*/
            function numberToUpperCase(number) {
                var uppercaseMonths = [
                    '一月', '二月', '三月', '四月', '五月', '六月',
                    '七月', '八月', '九月', '十月', '十一月', '十二月'
                ];
                return uppercaseMonths[number - 1];
            }
            var myDate = new Date();
            var result = numberToUpperCase(myDate.getMonth() + 1);
            $('.header-title').html("@Html.Raw(Label.Board_TestProcessYield)");
            function getTime() {
                var myDate = new Date();
                var myYear = myDate.getFullYear(); //年
                var myMonth = myDate.getMonth() + 1; //月
                var myToday = myDate.getDate(); //日
                var myDay = myDate.getDay(); //星期
                var myHour = myDate.getHours(); //小时
                var myMinute = myDate.getMinutes(); //分钟
                var mySecond = myDate.getSeconds(); //秒数
                var week = ['@Label.Sunday', '@Label.Monday', '@Label.Tuesday', '@Label.Wednesday', '@Label.Thursday', '@Label.Friday', '@Label.Saturday'];
                var nowTime;

                nowTime = myYear + '-' + fillZero(myMonth) + '-' + fillZero(myToday) + '&nbsp;&nbsp;' + fillZero(myHour) + ':' + fillZero(myMinute) + ':' + fillZero(mySecond) + '&nbsp;&nbsp;' + week[myDay] + '&nbsp;&nbsp;';
                $('#time').html(nowTime);
            };
            function fillZero(str) {
                var realNum;
                if (str < 10) {
                    realNum = '0' + str;
                } else {
                    realNum = str;
                }
                return realNum;
            }
            setInterval(getTime, 1000);

            // 设置全屏
            $('.dimension').on('click', function (e) {
                var element = document.documentElement;
                if ($(".dimension").text() == "@Html.Raw(Label.Full)") {
                    // 判断浏览器设备类型
                    if (element.requestFullscreen) {
                        element.requestFullscreen();
                    } else if (element.mozRequestFullScreen) {       //兼容火狐
                        element.mozRequestFullScreen();
                    } else if (element.webkitRequestFullscreen) {    //兼容谷歌
                        element.webkitRequestFullscreen();
                    } else if (element.msRequestFullscreen) {        //兼容IE
                        element.msRequestFullscreen();
                    }
                    $(".dimension").text("@Html.Raw(Label.Exit+Label.Full)");
                } else {
                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                    } else if (document.mozCancelFullScreen) {
                        document.mozCancelFullScreen();
                    } else if (document.webkitCancelFullScreen) {
                        document.webkitCancelFullScreen();
                    } else if (document.msExitFullscreen) {
                        document.msExitFullscreen();
                    }
                    $(".dimension").text("@Html.Raw(Label.Full)");
                }
            });
            $("#cmb_tester_type").css("display", "none");
            $('#btn_query').prop('disabled', true);
            $('#startdate').on('change', function () {
                var startDate = new Date($(this).val());
                var endDate = new Date($('#enddate').val());
                startDate.setDate(startDate.getDate() + 1);
                var minEndDate = startDate.toISOString().split('T')[0];
                $('#enddate').attr('min', minEndDate);
                if (endDate < startDate) {
                    $('#enddate').val($(this).val());
                }
            });
            $('#enddate').on('change', function () {
                var startDate = new Date($('#startdate').val());
                var endDate = new Date($(this).val());
                endDate.setDate(endDate.getDate() - 1);
                var maxStartDate = endDate.toISOString().split('T')[0];
                $('#startdate').attr('max', maxStartDate);
                if (startDate > endDate) {
                    $('#startdate').val($(this).val());
                }
            });
        });

        function setDateRange(){
            var now = new Date();
            now.setMinutes(now.getMinutes() + 1);
            var hours = now.getHours();
            var minutes = now.getMinutes();

            var startDate = new Date();
            //startDate.setMonth(startDate.getMonth() - 1);
            startDate.setDate(startDate.getDate() - 7);
            startDate.setHours(7, 0, 0, 0);
            var endDate = new Date();
            endDate.setHours(hours, minutes, 0, 0);
            var startdatetime = startDate.toLocaleDateString('sv-SE') + 'T' + startDate.toTimeString().slice(0, 5);
            $('#startdate').val(startdatetime);
            var enddatetime = endDate.toLocaleDateString('sv-SE') + 'T' + endDate.toTimeString().slice(0, 5);
            $('#enddate').val(enddatetime);
        }

        //初始化图表
        var memachinetype;
        var chartIds = ['chart1', 'chart2'];
        //图表自适应大小
        function echartsautomatic() {
            var charts = [];
            chartIds.forEach(function (chartId) {
                var chart = echarts.init(document.getElementById(chartId));
                charts.push(chart);
            });
            window.onresize = function () {
                charts.forEach(function (chart) {
                    chart.resize();
                });
            };
        }

        //图表最大
        function maxchart(id) {
            const chartElement = document.getElementById(id);
            if (chartElement) {
                const chart = echarts.getInstanceByDom(chartElement);
                if (chart) {
                    chart.setOption({
                        textStyle: { fontSize: '0.3rem' },
                        tooltip: {
                            textStyle: { fontSize: '0.3rem' }
                        },
                        legend: {
                            itemWidth: 20,
                            itemHeight: 20,
                            scrollDataIndex: 0,
                            pageIconSize: [25, 25],
                            pageIconColor: '#ffffff',
                            textStyle: { color: '#ffffff', fontSize: '0.25rem' },
                            pageTextStyle: { color: '#ffffff', fontSize: '0.25rem' },
                        },
                        grid: { top: '12%', left: '3%', right: '3%', width: '94%', containLabel: true },
                        xAxis: {
                            axisLabel: {
                                show: true,
                                textStyle: { color: 'white', fontSize: '0.25rem' }
                            }
                        },
                        yAxis: [
                            { axisLabel: { textStyle: { color: '#fff', fontSize: '0.25rem' } }, splitLine: { show: false } },
                            { axisLabel: { textStyle: { color: '#fff', fontSize: '0.25rem' } }, splitLine: { show: false } }
                        ]
                    });
                    const option = chart.getOption();
                    option.series.forEach((s) => {
                        if (s.type === 'line') {
                            s.lineStyle = { width: 4 };
                            s.symbolSize = 8;
                        }
                    });
                    chart.setOption(option);
                    chart.resize();
                }
            }
        }

        //图表最小
        function minchart(id) {
            $("#" + id).css("display", "none");
            setTimeout(() => {
                $("#" + id).css("display", "block");
                if (id == "chart1") {
                    switch (tablinkname) {
                        case "TesterPrime":
                            TesterPrimeYieldChartFun();
                            break;
                        case "FinalYield":
                            FinalYieldChartFun();
                            break;
                        case "FailureMode":
                            FailureModeAreaChartFun();
                            break;
                    }
                }
                if (id == "chart2") {
                    generatePlatoChart();
                }
            }, 1500);
        }

        /*Tab手动切换*/
        function OpenTab(evt, panle, id, echar_name, itemindex = -1) {
            $("#cmb_fail_type").val("ALL");
            $('#process_input').val('ALL');
            $('#cmb_data_type').val('WEEK');
            var i, tablinks;
            tablinks = document.getElementsByClassName(panle)[0].getElementsByClassName("tablinks");
            for (i = 0; i < tablinks.length; i++) {
                tablinks[i].className = tablinks[i].className.replace("active", "");
            }
            evt.currentTarget.className += " active";
            var chart = echarts.init(document.getElementById("chart1"));
            chart.dispose();
            echar_name();
            const tab = document.getElementById("yield_id") || document.getElementById("maximizedyieldchart");
            if (tab.id === "maximizedyieldchart") {
                maxchart(id);
            }
        }

        //下拉框
        $(function () {
            setDateRange();
            var projectsele = $("#cmb_proj_code");
            var processsele = $("#cmb_process_code");
            var pam = {};
            loadData(projectsele, api + '/ReportAction/GetProjCode', true);
            projectsele.change(function () {
                pam.proj_code = $(this).val();
                loadData(processsele, api + '/ReportAction/GetYielProcess', false);
            });
            var projcode = $("#projcode");
            var process = $("#process");
            loadData(projcode, api + '/ReportAction/GetProjCode', false);
            projcode.change(function () {
                pam.proj_code = $(this).val();
                loadData(process, api + '/ReportAction/GetTestProcess', false);
            });
            //$("#cmb_proj_code").val(1).trigger('change');
            //$("#cmb_proj_code").prop('selectedIndex', 1).trigger('change');
            $('#cmb_area_type').val('DG');
            $('#cmb_proj_code').val('NCCSAD').trigger('change');
            function loadData(selectElement, url, boolean) {
                $.ajax({
                    type: "POST",
                    url: url,
                    data: pam,
                    async: false,
                    dataType: "json",
                    success: function (data) {
                        selectdata = data.ReturnData;
                        selectElement.empty();
                        if (boolean) {
                            selectElement.append("<option value=''>@Html.Raw(Label.PleaseSelect)...</option>");
                        } else {
                            selectElement.append("<option value='ALL'>@Html.Raw(Label.ALL)</option>");
                        }
                        if (selectdata.length <= 0) {
                            var option = "<option>@Html.Raw(Label.No+Label.Correlation+Label.Data)</option>";
                            selectElement.append(option);
                            return;
                        }
                        $.each(selectdata, function (key, value) {
                            selectElement.append($('<option>', {
                                value: value.value,
                                text: value.text
                            }));
                        });
                    }
                });
            }
            getdata();
        });

        /*下拉框状态*/
        function stateselected() {
            var state = false;
            if ($('#cmb_proj_code').prop('selectedIndex') > 0 && $("#startdate").val() && $("#enddate").val()) {
                state = true;
            }
            return state;
        }

        //定时查询
        setInterval(() => {
            console.log("执行任务：", new Date().toLocaleTimeString());
            setDateRange();
            getdata();
        }, 120 * 60 * 1000);

        var getdata = function () {
            if (stateselected()) {
                boarddata();
                echartsautomatic();
            }
            else {
                alert("@Html.Raw(Label.PleaseSelect+Label.Required+Label.Where+Label.Item)");
            }
        }

        var ModalShow = function (type) {
            $("#Item").text("@Html.Raw(Label.Fail+Label.Message+Label.Maintain)");
            $(".modal").fadeIn();
        }

        var ExportType;
        var TestFailGroupExport = function () {
            ExportType = "TestFailGroup";
            var pam = {
                type: ExportType,
                proj_code: $('#projcode').val() == "" ? "ALL" : $('#projcode').val(),
                product_code: 'ALL',
                process_code: $('#process').val() == null ? "ALL" : $('#process').val()
            };
            var url = api + "/Dashboard/ExportToExcel?" + $.param(pam);
            ExportToExcel(url);
        }

        function ModalClose(modalname) {
            $("#export").empty();
            $("."+modalname+"").fadeOut();
        }

        //上传
        var UploadExcel = function () {
            var fileInput = document.getElementById("Template");
            var file = fileInput.files[0];
            var formData = new FormData();
            formData.append("file", file);
            //formData.append("type", uploadType);
            formData.append("type", "TestFailGroup");
            $.ajax({
                type: "POST",
                //url: "http://localhost:44304/Dashboard/UploadExcel",
                url: api + "/Dashboard/UploadExcel",
                enctype: 'multipart/form-data',
                data: formData,
                async: false,
                processData: false,// 禁止将数据转换为查询字符串
                contentType: false,// 禁止设置请求头的Content-Type
                crossDomain: true,
                success: function (data) {
                    if (data.Success) {
                        alert("successfully");
                        //$('#product').empty();
                        //$('#process').empty();
                        $("#Template").val('');
                        $("#message").val('');
                        $(".modal").fadeOut();
                    }
                }
            });

        };

        /*导出生产数据*/
        var TestDataExport = function (type) {
            if (stateselected()) {
                ExportType = type;
                var formData = new FormData();
                formData.append('type', ExportType);
                formData.append('proj_code', $('#cmb_proj_code').val());
                formData.append('process_id', $('#cmb_process_code').val() == null ? "ALL" : $('#cmb_process_code').val());
                formData.append('prodtype', $('#cmb_prod_type').val());
                formData.append('start_time', $("#startdate").val());
                formData.append('end_time', $("#enddate").val());
                formData.append('area', $("#cmb_area_type").val());
                var url = api + "/Dashboard/TestDataToExcel";
                PostExportToExcel(url, formData);
                alert("数据量过大。。。\n\n正在加速下载，请等待2分钟^_^");
            }
            else {
                alert("请先查询^_^")
            }
        }
        //报表导出
        var YieldReportExport = function (type) {
            var formData = new FormData();
            formData.append('proj_code', $('#cmb_proj_code').val());
            formData.append('prodtype', $('#cmb_prod_type').val());
            formData.append('process_id', $('#cmb_process_code').val() == null ? "ALL" : $('#cmb_process_code').val());
            formData.append('start', $("#startdate").val());
            formData.append('end', $("#enddate").val());
            formData.append('area', $("#cmb_area_type").val());
            ExportType = type;
            var url = api + "/ReportAction/YieldReportToExcel";
            PostExportToExcel(url, formData);
            alert("数据量过大。。。\n\n正在加速下载，请等待2分钟^_^");
        }
        //POST 参数不固定 导出
        var PostExportToExcel = function (url, formData) {
            //GET: var url = "http://localhost:44304/Dashboard/ExportToExcel?" + $.param(pam);
            var xhr = new XMLHttpRequest();
            xhr.open('POST', url, true);
            xhr.responseType = 'blob';
            xhr.onload = function () {
                if (xhr.status === 200) {
                    var url = window.URL.createObjectURL(xhr.response);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = ExportType.toLocaleUpperCase() + '.xlsx';
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            };
            xhr.send(formData);
        }

        //导出
        var ExportToExcel = function (url) {
            //var url = "http://localhost:44304/Dashboard/ExportToExcel?" + $.param(pam);
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.responseType = 'blob';
            xhr.onload = function () {
                if (xhr.status === 200) {
                    var url = window.URL.createObjectURL(xhr.response);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = ExportType.toLocaleUpperCase() + '.xlsx';
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            };
            /*
            GET:param
            var formData = new FormData();
            formData.append('CL_TYPE', $("#cmb_classtype").val());
            xhr.send(formData);
            */
            xhr.send();
        }

        function loadingshow() {
            $('tfoot').css('background-color', 'transparent');
            $('#table-container,#chart1,#chart2').css('background-image', 'url("../images/loading.gif")');
            $('#table-container,#chart1,#chart2').css('background-size', '0.8rem 0.8rem');
            $('#table-container,#chart1,#chart2').css('background-repeat', 'no-repeat');
            $('#table-container,#chart1,#chart2').css('background-position', 'center');
        }
        function loadingnone() {
            $('tfoot').css('background-color', '#09314e');
            $('#table-container,#chart1,#chart2').css('background-image', 'none');
        }

        //报表
        var dataset;
        var boarddata = function () {
            $('#btn_query').prop('disabled', true);
            $("#yield_tbody, #sum, #primeyield, #finalyield").empty();
            var pam = {};
            pam.proj_code = $('#cmb_proj_code').val();
            pam.process = $('#cmb_process_code').val();
            pam.prodtype = $('#cmb_prod_type').val();
            pam.start = $("#startdate").val();
            pam.end = $("#enddate").val();
            pam.area = $("#cmb_area_type").val();
            if (pam.proj_code !== "-1") {
                loadingshow();
                $.ajax({
                    type: "POST",
                    url: "/Report/Getdata",
                    data: pam,
                    dataType: "json",
                    success: function (data) {
                        loadingnone();
                        $('#btn_query').prop('disabled', false);
                        $("#yield_tbody, #sum, #primeyield, #finalyield").empty();
                        dataset = data;
                        TesterPrimeYieldChartFun();
                        generatePlatoChart();
                        process_search_binding();
                        failuremode_binding();
                        platotester_binding();
                        var table = "";
                        var primeyield, finalyield;
                        for (var i = 0; i < data.yield.length; i++) {
                            var zebracro = i % 2;
                            if (data.yield[i].row_id && parseInt(data.yield[i].row_id) > 0) {
                                table += '<tr ' + (zebracro == 0 ? 'class="zebracro"' : '') + '>'
                                    + '<td class="tabletd" rowspan=' + data.yield[i].rowspan + '>' + data.yield[i].process_id + '</td>'
                                    + '<td class="tabletd" rowspan=' + data.yield[i].rowspan + '>' + data.yield[i].input_qty + '</td>'
                                    + '<td class="tabletd" rowspan=' + data.yield[i].rowspan + '>' + data.yield[i].output_qty + '</td>'
                                    + '<td class="tabletd" rowspan=' + data.yield[i].rowspan + '>' + data.yield[i].prime_yield + '</td>'
                                    + '<td class="tabletd" rowspan=' + data.yield[i].rowspan + '>' + data.yield[i].final_yield + '</td>'
                                    + '<td>' + data.yield[i].failure_mode + '</td>'
                                    + '<td class="tabletd">' + data.yield[i].prime_reject + '</td>'
                                    + '<td class="tabletd">' + data.yield[i].retest_pass + '</td>'
                                    + '<td class="tabletd">' + data.yield[i].prime_reject_rate + '</td>'
                                    + '<td class="tabletd">' + data.yield[i].final_reject_rate + '</td>'
                                    + '</tr>';
                                var primeyieldFloat = parseFloat(data.yield[i].prime_yield.substring(0, data.yield[i].prime_yield.indexOf("%"))) / 100;
                                var finalyieldFloat = parseFloat(data.yield[i].final_yield.substring(0, data.yield[i].final_yield.indexOf("%"))) / 100;
                                if (!(primeyield)) {
                                    primeyield = (primeyieldFloat > 0 ? primeyieldFloat : 1);
                                }
                                else {
                                    primeyield = primeyield * (primeyieldFloat > 0 ? primeyieldFloat : 1);
                                }
                                if (!(finalyield)) {
                                    finalyield = (finalyieldFloat > 0 ? finalyieldFloat : 1);
                                }
                                else {
                                    finalyield = finalyield * (finalyieldFloat > 0 ? finalyieldFloat : 1);
                                }
                            }
                            else {
                                table += '<tr ' + (zebracro == 0 ? 'class="zebracro"' : '') + '>'
                                    + '<td>' + data.yield[i].failure_mode + '</td>'
                                    + '<td class="tabletd">' + data.yield[i].prime_reject + '</td>'
                                    + '<td class="tabletd">' + data.yield[i].retest_pass + '</td>'
                                    + '<td class="tabletd">' + data.yield[i].prime_reject_rate + '</td>'
                                    + '<td class="tabletd">' + data.yield[i].final_reject_rate + '</td>'
                                    + '</tr>';
                            }
                        }
                        $('#yield_tbody').html(table);
                        $("#sum").text("@Html.Raw(Label.Summary)");
                        $('#primeyield').html(parseFloat((primeyield * 100).toFixed(2)) + "%");
                        $('#finalyield').html(parseFloat((finalyield * 100).toFixed(2)) + "%");
                    }
                });
            }
        };

        var failuremode_binding = function(){
            var cmbfail = $('#cmb_failuremode');
            var data = JSON.parse(dataset.yieldmachine[0].tester_failure_mode_prime_yield_json);
            cmbfail.find("option:not([value='ALL'])").remove();
            const failureModes = [];
            data.forEach(item => {
                const mode = item.FAILURE_MODE;
                if (mode !== "NULL" && failureModes.indexOf(mode) === -1) {
                    failureModes.push(mode);
                }
            });
            failureModes.forEach(mode => {
                if (!cmbfail.find(`option[value="${mode}"]`).length) {
                    cmbfail.append(`<option value="${mode}">${mode}</option>`);
                }
            });
        }

        var platotester_binding = function () {
            var cmbtester = $('#cmb_tester_type');
            var data = JSON.parse(dataset.failuremodeplato[0].prime_plato_tester_json);
            cmbtester.find("option:not([value='ALL'])").remove();
            const failureTester = [];
            data.forEach(item => {
                const tester = item.TESTER;
                if (tester !== "NULL" && failureTester.indexOf(tester) === -1) {
                    failureTester.push(tester);
                }
            });
            failureTester.forEach(tester => {
                if (!cmbtester.find(`option[value="${tester}"]`).length) {
                    cmbtester.append(`<option value="${tester}">${tester}</option>`);
                }
            });
        }

        var tablinkname;
        var tablinksonclick = function (switch_on) {
            tablinkname = switch_on;
            $("#cmb_fail_type").val("ALL");
            $('#cmb_data_type').val('WEEK');
            var i, tablinks;
            tablinks = document.getElementsByClassName('tab')[0].getElementsByClassName("tablinks");
            for (i = 0; i < tablinks.length; i++) {
                tablinks[i].className = tablinks[i].className.replace("active", "");
            }
            switch (switch_on) {
                case "TesterPrime":
                    tablinks[0].className += " active";
                    $("#cmb_fail_type").css("display", "block");
                    $("#cmb_type").css("display", "none");
                    $(".search").css("display", "none");
                    break;
                case "FinalYield":
                    tablinks[1].className += " active";
                    $("#cmb_fail_type").css("display", "none");
                    $("#cmb_type").css("display", "block");
                    $(".search").css("display", "none");
                    break;
                case "FailureMode":
                    tablinks[2].className += " active";
                    $("#cmb_fail_type").css("display", "none");
                    $("#cmb_type").css("display", "block");
                    $(".search").css("display", "block");
                    break;
                default:
                    tablinkname = "TesterPrime";
                    break;
            }
        }

        //process 搜索下拉绑定
        var process_search_binding = function () {
            var processSearch = $('#process_search');
            processSearch.empty();
            var processSet = new Set();
            $.each(dataset.rejectrateWeek, function (index, item) {
                var process = item.process_id.trim();
                processSet.add(process);
            });
            processSearch.append($('<option>').val('ALL'));
            processSet.forEach(function (process) {
                processSearch.append($('<option>').val(process));
            });
            $('#process_input').val('ALL');
        }

        $('#cmb_failuremode').on('change', function () {
            TesterPrimeYieldChartFun();
        });
        $('#cmb_plato_type, #cmb_tester_type').on('change', function () {
            var platoValue = $('#cmb_plato_type').val();
            if (platoValue == "FinalPlato") {
                $("#cmb_tester_type").css("display", "none");
                $('#cmb_tester_type').val('ALL');
            } else if (platoValue == "PrimePlato") {
                $("#cmb_tester_type").css("display", "block");
            }
            generatePlatoChart();
        });

        //下拉月周日页签联动
        $('#cmb_data_type,#process_input').on('change', function () {
            var i, tablinks, fun, action;
            tablinks = document.getElementsByClassName("tab")[0].getElementsByClassName("tablinks");
            for (i = 0; i < tablinks.length; i++) {
                if (tablinks[i].className.includes("active")) {
                    switch (i) {
                        case 0:
                            action = "TesterPrime";
                            fun = testerprimeyieldchart;
                            break;
                        case 1:
                            action = "FinalYield";
                            fun = finalyieldchart;
                            break;
                        case 2:
                            action = "FailureMode";
                            fun = failuremodeareachart;
                            break;
                    }
                }
            }
            updateTabChart(fun, action);
            const tab = document.getElementById("yield_id") || document.getElementById("maximizedyieldchart");
            if (tab.id === "maximizedyieldchart") {
                maxchart("chart1");
            }
        });

        //updateChart
        var updateTabChart = function (fun, actionname) {
            var process = $('#process_input').val();
            var cl_type = $('#cmb_data_type').val();
            if (!fun) return;
            var updatechartdata;
            var dataZoomConfig = [];
            const actionMap = {
                FinalYield: {
                    week: dataset.finalyieldWeek,
                    day: dataset.finalyieldDay,
                    updateFunc: updateFinalYieldChartOptions
                },
                FailureMode: {
                    week: dataset.rejectrateWeek,
                    day: dataset.rejectrateDay,
                    updateFunc: updateFailureModeAreaChartOptions
                },
            };
            const commonDataZoomConfig = [
                {
                    type: 'inside',
                    start: 0,
                    end: 100,
                    xAxisIndex: [0, 1]
                },
                {
                    type: 'slider',
                    start: 0,
                    end: 100,
                    xAxisIndex: [0, 1],
                    handleSize: 0,
                    height: "0.3rem",
                    show: false,
                    zoomOnMouseWheel: true
                }
            ];
            for (let key in actionMap) {
                if (actionname == key) {
                    const actionConfig = actionMap[key];
                    updatechartdata = actionConfig[cl_type.toLowerCase()];
                    if (cl_type.toLowerCase() === 'day') {
                        dataZoomConfig = commonDataZoomConfig;
                    }
                    if (actionname == "FailureMode" && process !== "ALL") {
                        updatechartdata = updatechartdata.filter(item => item.process_id == process);
                    }
                    actionConfig.updateFunc(updatechartdata, dataZoomConfig);
                    break;
                }
            }
        };

        //TesterPrimeyield
        var testerprimeyieldchart;
        var testerprimeyieldloop;
        function TesterPrimeYieldChartFun() {
            var failuremode = $('#cmb_failuremode').val();
            var data;
            if(failuremode =="ALL"){
                data = JSON.parse(dataset.yieldmachine[0].tester_prime_yield_json);
            }
            else{
                var failure = JSON.parse(dataset.yieldmachine[0].tester_failure_mode_prime_yield_json);
                data = failure.filter(data => data.FAILURE_MODE == failuremode);
            }
            tablinksonclick("TesterPrime");
            var colorList = ['#338AF6', '#78C77D', '#F4D35F', '#435184', '#8C67DE', '#6BC8CA', '#0AAF9F', '#E89589', '#16A085', '#4A235A', '#C39BD3 ', '#F9E79F', '#BA4A00', '#ECF0F1', '#616A6B', '#EAF2F8', '#4A235A', '#3498DB'];
            var chartDom = document.getElementById("chart1");
            if (chartDom) {
                echarts.dispose(chartDom);
            }
            var myChart = echarts.init(chartDom);
            var machineitem = [];
            var itemvaule = [];
            var itemcolor = [];
            var linevaule = [];
            if (data) {
                for (var i = 0; i < data.length; i++) {
                    machineitem.push(data[i].TESTER);
                    itemvaule.push(data[i].PRIME_REJECT);
                    itemcolor.push(colorList[parseInt(data[i].SORT)]);
                    linevaule.push(parseInt(data[i].TESTER_PRIME_YIELD));
                }
            };
            var linemax = Math.max.apply(null, linevaule);
            var option = {
                textStyle: {
                    color: '#fff',
                    fontSize: '0.14rem'
                },
                tooltip: {
                    show: true,
                    trigger: 'axis',
                    backgroundColor: '#007297',
                    textStyle: {
                        fontSize: '0.14rem'
                    },
                    axisPointer: {
                        type: 'cross',
                    },
                    formatter: function (params) {
                        let dataItem = data.find(data => data.TESTER == params[0].axisValue);
                        if (dataItem) {
                            let tooltipText = `
                            <div style="background-color: #007297;">
                                <p>${params[0].marker}${dataItem.PROCESS_ID}：${params[0].axisValue}</p>
                                <table style="background-color: #007297;">
                                    <tr>
                                        <td>Input:${dataItem.INPUT}</td>
                                        <td>Pass:${dataItem.PASS}</td>
                                        <td>PrimeReject:${dataItem.PRIME_REJECT}</td>
                                        <td>PrimeYield:${dataItem.TESTER_PRIME_YIELD}%</td>
                                    </tr>
                                </table>
                            </div>`;
                            return tooltipText;
                        }
                    }
                },
                grid: {
                    top: '10%',
                    left: '7%',
                    right: '7%',
                    //bottom: '28%',
                    width: '86%'
                },
                xAxis: [
                    {
                        type: 'category',
                        data: machineitem,
                        axisTick: {
                            alignWithLabel: true
                        },
                        axisLabel: {
                            show: true,
                            interval: machineitem.length > 30 ? Math.floor(machineitem.length / 30) : 0,
                            rotate: 45,
                            textStyle: {
                                color: 'white',
                                fontSize: '0.12rem'
                            }
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        name: 'PrimeReject',
                        //min: 0,
                        //max: Math.ceil(vaulemax),
                        //interval: Math.ceil(vaulemax / 6),
                        scale: true,//刻度范围一致
                        splitLine: { show: false },
                        yAxisIndex: 0,
                        axisTick: { //y轴刻度线
                            show: true
                        },
                        axisLine: { //y轴
                            show: true
                        },
                        axisLabel: {
                            textStyle: {
                                color: '#fff',
                                fontSize: '0.12rem'
                            }
                        }
                    },
                    {
                        type: 'value',
                        name: 'PrimeYield',
                        min: 0,
                        max: 100,
                        // interval: 20,
                        scale: true,//刻度范围一致
                        splitLine: { show: false },
                        yAxisIndex: 1,
                        axisTick: { //y轴刻度线
                            show: true
                        },
                        axisLine: { //y轴
                            show: true
                        },
                        axisLabel: {
                            formatter: function (value) {
                                return value + '%';
                            },
                            textStyle: {
                                color: '#fff',
                                fontSize: '0.12rem'
                            }
                        }
                    }
                ],
                dataZoom: [
                    {
                        type: 'inside',
                        yAxisIndex: 1,
                        zoomLock: false
                    },
                    {
                        type: 'slider',
                        yAxisIndex: 1,
                        zoomLock: false,
                        right: 1,
                        width: 10
                    }
                ],
                series: [
                    {
                        name: 'PrimeReject',
                        type: 'bar',
                        barWidth: '50%',
                        itemStyle: {
                            normal: {
                                color: function (params) {
                                    var colorList = itemcolor;
                                    return colorList[params.dataIndex]
                                }
                            }
                        },
                        data: itemvaule
                    },
                    {
                        name: 'PrimeYield',
                        type: 'line',
                        yAxisIndex: 1,
                        silent: true,
                        itemStyle: {
                            color: '#FC8452',
                            Width: 2
                        },
                        itemStyle: { normal: { color: '#FC8452 ' } },
                        areaStyle: {
                            normal: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1,
                                    [
                                        { offset: 0, color: 'rgba(237, 178, 23, 0.5)' },
                                        { offset: 0.8, color: 'rgba(237, 178, 23, 0.1)' }
                                    ], false),
                                shadowColor: 'rgba(0, 0, 0, 0.1)',
                                shadowBlur: 1
                            }
                        },
                        data: linevaule,
                        tooltip: {
                            valueFormatter: function (value) {
                                return value + ' %';
                            }
                        }
                    }
                ]
            };
            myChart.setOption(option);
            //loopShow(testerprimeyieldloop, myChart);
            //柱状图点击事件：切换为折线图
            myChart.off('click');
            myChart.on('click', function (params) {
                if (params.componentType === 'series' && params.seriesType === 'bar') {
                    var selectedTester = params.name;
                    var allDayData = JSON.parse(dataset.yieldmachine[0].tester_day_prime_yield_json);
                    var testerDayData = allDayData.filter(d => d.TESTER === selectedTester);
                    testerDayData.sort((a, b) => new Date(`${a.YEAR}-${a.DATE}`) - new Date(`${b.YEAR}-${b.DATE}`));
                    var dateList = testerDayData.map(d => d.DATE);
                    var yieldList = testerDayData.map(d => d.PRIME_YIELD);
                    var newOption = {
                        title: {
                            text: `${selectedTester} By Day Prime Yield`,
                            left: 'left',
                            textStyle: { color: '#fff', fontSize: '0.14rem'}
                        },
                        tooltip: {
                            trigger: 'axis',
                            backgroundColor: '#007297',
                            textStyle: {
                                fontSize: '0.14rem',
                                color: '#fff'
                            },
                            formatter: function (params) {
                                let dataItem = testerDayData.find(data => data.DATE == params[0].axisValue);
                                if (dataItem) {
                                    let tooltipText = `
                                    <div style="background-color: #007297;">
                                        <p>${dataItem.DATE}</p>
                                        <p>${params[0].marker}${dataItem.PROCESS_ID}：${dataItem.TESTER}</p>
                                        <table style="background-color: #007297;">
                                            <tr>
                                                <td>Input:${dataItem.INPUT}</td>
                                                <td>Pass:${dataItem.OUTPUT}</td>
                                                <td>PrimeReject:${dataItem.REJECT}</td>
                                                <td>PrimeYield:${dataItem.PRIME_YIELD}%</td>
                                            </tr>
                                        </table>
                                    </div>`;
                                    return tooltipText;
                                }
                            }
                        },
                        toolbox: {
                            feature: {
                                saveAsImage: {
                                    show: false,
                                    name:`${selectedTester}PrimeYield`
                                }
                            }
                        },
                        graphic: {
                          elements: [{
                            type: 'text',
                            left: 'right',
                            top: '0.14rem',
                            style: {
                              text: '返回总览',
                              font: '0.14rem sans-serif',
                              fill: '#fff',
                              backgroundColor: 'rgba(0,0,0,0.3)',
                              padding: [4, 8],
                              borderRadius: 5,
                              cursor: 'pointer',
                              shadowBlur: 5,
                              shadowColor: 'rgba(0,0,0,0.3)'
                            },
                            onclick: function () {
                                TesterPrimeYieldChartFun(); 
                            }
                          }]
                        },
                        grid: { top: '15%', left: '6%', right: '5%', bottom: '10%', width: '89%'},
                        xAxis: {
                            type: 'category',
                            data: dateList,
                            axisLabel: {
                                color: '#fff',
                                fontSize: '0.12rem'
                            }
                        },
                        yAxis: {
                            type: 'value',
                            yAxisIndex: 0,
                            min: 0,
                            max: 100,
                            axisLabel: {
                                formatter: '{value}%',
                                color: '#fff',
                                fontSize: '0.12rem'
                            }
                        },
                        dataZoom: [
                            {
                                type: 'inside',
                                yAxisIndex: 0,
                                zoomLock: false
                            },
                            {
                                type: 'slider',
                                yAxisIndex: 0,
                                zoomLock: false,
                                right: 1,
                                width: 10
                            }
                        ],
                        series: [{
                            name: 'PrimeYield',
                            type: 'line',
                            data: yieldList,
                            smooth: true,
                            itemStyle: { color: '#00C598' },
                            areaStyle: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    { offset: 0, color: 'rgba(0, 197, 152, 0.5)' },
                                    { offset: 1, color: 'rgba(0, 197, 152, 0.1)' }
                                ])
                            }
                        }]
                    };
                    myChart.setOption(newOption, true);
                }
            });

        };

        //finalyieldchart
        var finalyieldchart;
        function FinalYieldChartFun() {
            tablinksonclick("FinalYield");
            var chartData = dataset.finalyieldWeek;
            var chartDom = document.getElementById("chart1");
            if (chartDom) {
                echarts.dispose(chartDom);
            }
            finalyieldchart = echarts.init(chartDom);
            updateFinalYieldChartOptions(chartData, null);
        }
        var updateFinalYieldChartOptions = function (chartData, dataZoomConfig) {
            var groupedData = {};
            chartData.forEach(function (item) {
                if (!groupedData[item.process_id]) {
                    groupedData[item.process_id] = {
                        date: [],
                        final_yield: []
                    };
                }
                groupedData[item.process_id].date.push(item.date);
                groupedData[item.process_id].final_yield.push(item.final_yield.replace('%', ''));
            });
            var seriesData = Object.keys(groupedData).map(function (processId) {
                return {
                    name: processId,
                    type: 'line',
                    data: groupedData[processId].final_yield.map(value => value === null ? 0 : value),
                    emphasis: {
                        focus: 'series',
                        lineStyle: {
                            opacity: 2
                        },
                        itemStyle: {
                            opacity: 2
                        }
                    },
                    tooltip: {
                        valueFormatter: function (value) {
                            return value + '%';
                        }
                    }
                };
            });
            var xAxisdata;
            if ($('#cmb_data_type').val() === 'WEEK') {
                xAxisdata = chartData.map(item => item.date).filter((value, index, self) => self.indexOf(value) === index);
            }
            else {
                xAxisdata = Array.from(new Set(chartData.map(item => item.date))).sort((a, b) => new Date(`2024-${a.replace("-", "/")}`) - new Date(`2024-${b.replace("-", "/")}`));
            }
            var option = {
                textStyle: {
                    color: '#fff',
                    fontSize: '0.16rem'
                },
                tooltip: {
                    show: true,
                    trigger: 'item',
                    color: 'red',
                    textStyle: {
                        color: '#666666',
                        fontSize: '0.14rem'
                    },
                    axisPointer: {
                        type: 'line'
                    },
                    formatter: function (param) {
                        let axisValue = param.axisValue || param.name;
                        let dataItem = chartData.find(data => data.date == axisValue && data.process_id == param.seriesName);
                        if (!dataItem) return '';
                        return `
                            <div class="tooltip">${param.marker}${param.seriesName}(${axisValue})</div>
                            <table>
                                <tr><td class="tooltip">Input: ${dataItem.input}</td></tr>
                                <tr><td class="tooltip">Output: ${dataItem.output}</td></tr>
                                <tr><td class="tooltip">Reject: ${dataItem.reject}</td></tr>
                                <tr><td class="tooltip">PrimeYield: ${dataItem.prime_yield}</td></tr>
                                <tr><td class="tooltip">RetestPass: ${dataItem.retest_pass}</td></tr>
                                <tr><td class="tooltip">FinalYield: ${dataItem.final_yield}</td></tr>
                            </table>
                        `;
                    },
                },
                legend: {
                    show: true,
                    type: 'scroll',
                    width: '100%',
                    data: Object.keys(groupedData),
                    orient: 'horizontal',
                    itemWidth: 12,
                    itemHeight: 12,
                    scrollDataIndex: 0,
                    pageIconSize: [16, 16],
                    pageIconColor: '#ffffff',
                    textStyle: {
                        color: '#ffffff',
                        fontSize: '0.16rem'
                    },
                    pageTextStyle: {
                        color: '#ffffff',
                        fontSize: '0.16rem',
                    },
                    pageButtonItemHoverColor: '#0aa9cd'
                },
                grid: {
                    top: '20%',
                    left: '7%',
                    right: '2%',
                    bottom: '10%',
                    width: '90%',
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: xAxisdata,
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: true
                    },
                    axisLabel: {
                        textStyle: {
                            fontSize: '0.14rem'
                        },
                        show: true
                    }
                },
                yAxis: {
                    type: 'value',
                    name: 'FinalYield(%)',
                    //min: 20,
                    //max: 120,
                    //interval: 20,
                    scale: true,
                    axisTick: {
                        show: true
                    },
                    axisLabel: {
                        formatter: function (value) {
                            return value + '%';
                        },
                        textStyle: {
                            fontSize: '0.14rem'
                        },
                        show: true
                    }
                },
                series: seriesData,
                dataZoom: dataZoomConfig
            };
            finalyieldchart.setOption(option, true);
        };

        //failuremodeareachart
        var failuremodeareachart;
        function FailureModeAreaChartFun() {
            tablinksonclick("FailureMode");
            var chartData = dataset.rejectrateWeek;
            var chartDom = document.getElementById("chart1");
            if (chartDom) {
                echarts.dispose(chartDom);
            }
            failuremodeareachart = echarts.init(chartDom);
            updateFailureModeAreaChartOptions(chartData, null);
        }
        var updateFailureModeAreaChartOptions = function (chartData, dataZoomConfig) {
            console.log(JSON.stringify(chartData));
            var xAxisdata;
            if ($('#cmb_data_type').val() === 'WEEK') {
                xAxisdata = chartData.map(item => item.date)
                    .filter((value, index, self) => self.indexOf(value) === index)
                    .sort((a, b) => a - b);
            }
            else {
                xAxisdata = chartData
                    .map(item => item.date)
                    .filter((value, index, self) => self.indexOf(value) === index)
                    .sort((a, b) => new Date(`2024-${a.replace("-", "/")}`) - new Date(`2024-${b.replace("-", "/")}`));
            }
            var groupedData = {};
            chartData.forEach(function (item) {
                if (!groupedData[item.failure_mode]) {
                    groupedData[item.failure_mode] = {
                        DATE: [...xAxisdata],
                        REJECT_RATE: new Array(xAxisdata.length).fill(null)
                    };
                }
                var index = xAxisdata.indexOf(item.date);
                groupedData[item.failure_mode].REJECT_RATE[index] = item.final_reject_rate.replace('%', '');
            });
            var colorList = [
                ['#80FFA5', '#00FF88'],
                ['#00DDFF', '#0096FF'],
                ['#37A2FF', '#188DF0'],
                ['#FF0087', '#FF5D77'],
                ['#FFBF00', '#FFD700'],
                ['#FF7F50', '#FF4500'],
                ['#FF6347', '#FF4500'],
                ['#FFA07A', '#FF6347'],
                ['#FFD700', '#FFBF00'],
                ['#FFC1C1', '#FF6A6A'],
                ['#FFA500', '#FF8C00'],
                ['#FFDAB9', '#FFC1C1']
            ];
            var seriesData = Object.keys(groupedData).map(function (defect, index) {
                var colorGradient = colorList[index % colorList.length];
                return {
                    name: defect,
                    type: 'line',
                    stack: 'Total',
                    smooth: false,
                    showSymbol: true,
                    //itemStyle: { opacity: 0 },
                    lineStyle: { width: 0 },
                    emphasis: {
                        focus: 'series',
                        symbol: 'circle',
                        symbolSize: 8
                    },
                    areaStyle: {
                        normal: {
                            opacity: 0.8,
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: colorGradient[0] },
                                { offset: 1, color: colorGradient[1] }
                            ])
                        }
                    },
                    data: groupedData[defect].REJECT_RATE.map(value => value === null ? 0 : value)
                };
            });
            var option = {
                color: Object.keys(groupedData).map(function (defect, index) {
                    return colorList[index % colorList.length][0];
                }),
                textStyle: {
                    color: '#fff',
                    fontSize: '0.16rem'
                },
                tooltip: {
                    show: true,
                    trigger: 'item',
                      backgroundColor: '#007297',
                    textStyle: {
                        color: '#fff',
                        fontSize: '0.14rem'
                    },
                    axisPointer: {
                        type: 'cross',
                    },
                    formatter: function (params) {
                        let param = Array.isArray(params) ? params[0] : params;
                        let dataItem = chartData.find(data => data.date == param.name && data.failure_mode == param.seriesName);
                        if (dataItem) {
                            let tooltipText = `
                            <div style="background-color: #007297;">
                                <p>${dataItem.date}</p>
                                <p>${param.marker}${dataItem.process_id}：${dataItem.failure_mode}</p>
                                <table style="background-color: #007297;">
                                    <tr>
                                        <td>Reject:${dataItem.reject}</td>
                                        <td>RetestPass:${dataItem.retest_pass}</td>
                                        <td>FinalRejectRate:${dataItem.final_reject_rate}</td>
                                    </tr>
                                </table>
                            </div>`;
                            return tooltipText;
                        }
                    }
                },
                legend: {
                    show: true,
                    type: 'scroll',
                    width: '100%',
                    data: Object.keys(groupedData),
                    orient: 'horizontal',
                    itemWidth: 12,
                    itemHeight: 12,
                    scrollDataIndex: 0,
                    pageIconSize: [16, 16],
                    pageIconColor: '#ffffff',
                    textStyle: {
                        color: '#ffffff',
                        fontSize: '0.16rem'
                    },
                    pageTextStyle: {
                        color: '#ffffff' ,
                        fontSize: '0.16rem',
                    },
                    pageButtonItemHoverColor: '#0aa9cd'
                },
                grid: {
                    top: '20%',
                    left: '7%',
                    right: '2%',
                    bottom: '10%',
                    width: '90%',
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: xAxisdata,
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: true
                    },
                    axisLabel: {
                        textStyle: {
                            color: '#fff',
                            fontSize: '0.14rem'
                        },
                        show: true
                    }
                },
                yAxis: {
                    type: 'value',
                    name: 'FinalReject',
                    scale: true,
                    axisTick: {
                        show: true
                    },
                    axisLabel: {
                        formatter: function (value) {
                            return value + '%';
                        },
                        textStyle: {
                            color: '#fff',
                            fontSize: '0.14rem'
                        },
                        show: true
                    }
                },
                series: seriesData,
                dataZoom: dataZoomConfig
            };
            failuremodeareachart.setOption(option, true);
        };

        var platooptionloop;
        function generatePlatoChart() {
            var cmbplatotype = $('#cmb_plato_type').val();
            var cmbtester = $('#cmb_tester_type').val();
            var chart = document.getElementById("chart2");
            if (chart) {
                echarts.dispose(chart);
            }
            var myChart = echarts.init(chart);
            var item = [];
            var itemvaule = [];
            var linevaule = [];
            var lastvaule = 0;
            var data;

            // 根据类型选择数据
            if (cmbplatotype == "PrimePlato" && cmbtester != "ALL") {
                // PrimePlatoByTester
                var primetesterdata = JSON.parse(dataset.failuremodeplato[0].prime_plato_tester_json);
                data = primetesterdata.filter(data => data.TESTER == cmbtester);
            } else if (cmbplatotype == "PrimePlato") {
                // PrimePlato ALL
                data = JSON.parse(dataset.failuremodeplato[0].prime_plato_json);
            } else {
                // FinalPlato
                data = JSON.parse(dataset.failuremodeplato[0].final_plato_json);
            }
            if (data) {
                for (var i = 0; i < data.length; i++) {
                    item.push(data[i].FAILURE_MODE);
                    if (cmbplatotype == "PrimePlato") {
                        itemvaule.push(data[i].PRIME_REJECT_RATE);
                    } else {
                        itemvaule.push(data[i].FINAL_REJECT_RATE);
                    }
                    if (i == 0) {
                        lastvaule = data[i].PLATO_VAULE;
                        linevaule.push(data[i].PLATO_VAULE);
                    } else {
                        if (cmbtester != "ALL") {
                            lastvaule = data[i].PLATO_VAULE;
                        } else {
                            lastvaule += data[i].PLATO_VAULE;
                        }
                        linevaule.push(lastvaule.toFixed(2));
                    }
                }
            }
            var itemvaulemax = Math.max.apply(null, itemvaule);
            var yAxisName = cmbplatotype == "PrimePlato" ? "PrimeRejectRate" : "FinalRejectRate";
            var lineName = cmbplatotype == "PrimePlato" ? "PrimePlato" : "Proportion";
            // 生成ECharts配置
            var option = {
                textStyle: {
                    color: '#fff',
                    fontSize: '0.14rem'
                },
                tooltip: {
                    show: true,
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                        crossStyle: {
                            color: 'white'
                        }
                    },
                    formatter: function (params) {
                        var index = params[0].dataIndex;
                        var result = '';
                        params.forEach(function (item) {
                            result += `${item.marker} ${item.seriesName}：${item.value}%<br/>`;
                        });
                        var retest;
                        if (cmbplatotype == "PrimePlato"){
                            if (cmbtester != "ALL") {
                                //PRIME: PRIME_REJECT = PRIME_REJECT
                                retest= (data[index].PRIME_REJECT || 0);
                            } else {
                                //PRIME: PRIME_REJECT = FAILURE_REJECT
                                retest= (data[index].FAILURE_REJECT || 0);
                            }
                        }
                        if (cmbplatotype == "FinalPlato"){
                            //FINAL: FINAL_RETEST = PRIME_REJECT-RETEST_PASS
                            retest= (data[index].PRIME_REJECT || 0) - (data[index].RETEST_PASS || 0);
                        }
                        result += '🔧Retest : ' + retest + '<br/>';
                        return result;
                    }
                },
                grid: {
                    top: '10%',
                    left: '7%',
                    right: '7%',
                    width: '86%'
                },
                xAxis: [
                    {
                        type: 'category',
                        data: item,
                        axisLabel: {
                            show: true,
                            interval: item.length > 30 ? Math.floor(item.length / 30) : 0,
                            rotate: 45,
                            textStyle: {
                                color: 'white',
                                fontSize: '0.12rem'
                            }
                        },
                        axisPointer: {
                            type: 'shadow'
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        name: yAxisName,
                        min: 0,
                        max: Math.ceil(itemvaulemax),
                        interval: Math.ceil(itemvaulemax) / 5,
                        scale: true,
                        splitLine: { show: false },
                        axisTick: { show: true },
                        axisLine: { show: true },
                        axisLabel: {
                            show: true,
                            formatter: '{value} %',
                            textStyle: {
                                color: 'white',
                                fontSize: '0.12rem'
                            }
                        }
                    },
                    {
                        type: 'value',
                        name: lineName,
                        min: 0,
                        max: 100,
                        interval: 20,
                        scale: true,
                        splitLine: { show: false },
                        axisTick: { show: true },
                        axisLine: { show: true },
                        axisLabel: {
                            show: true,
                            formatter: '{value} %',
                            textStyle: {
                                color: 'white',
                                fontSize: '0.12rem'
                            }
                        }
                    }
                ],
                series: [
                    {
                        name: cmbplatotype == "PrimePlato" ? 'Prime Rate' : 'Failure Rate',
                        type: 'bar',
                        itemStyle: {
                            normal: {
                                barBorderRadius: [10, 10, 0, 0],
                                color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [{
                                    offset: 0,
                                    color: "#009AFD"
                                }, {
                                    offset: 0.8,
                                    color: "#33DAFF"
                                }], false),
                                shadowColor: 'rgba(0, 0, 0, 0.1)',
                            }
                        },
                        tooltip: {
                            valueFormatter: function (value) {
                                return value + ' %';
                            }
                        },
                        data: itemvaule
                    },
                    {
                        name: lineName,
                        type: 'line',
                        yAxisIndex: 1,
                        itemStyle: { normal: { color: '#00C598 ' } },
                        areaStyle: {
                            normal: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1,
                                    [
                                        { offset: 0, color: 'rgba(0, 197, 152, 0.5)' },
                                        { offset: 0.8, color: 'rgba(0, 197, 152, 0.1)' }
                                    ], false),
                                shadowColor: 'rgba(0, 0, 0, 0.1)',
                                shadowBlur: 1
                            }
                        },
                        tooltip: {
                            valueFormatter: function (value) {
                                return value + ' %';
                            }
                        },
                        data: linevaule
                    }
                ]
            };
            myChart.setOption(option);
            //loopShow(platooptionloop, myChart);
        }

        function loopShow(pamloop, chart) {
            if (pamloop) {
                pamloop = null;
            }
            pamloop = tools.loopShowTooltip(chart, option, { loopSeries: true });
        }

        var maximized = false;
        function toggleMaximize(elementId, maximizedId, chartId) {
            const tab = document.getElementById(elementId) || document.getElementById(maximizedId);
            if (tab) {
                if (tab.id === elementId) {
                    maximized = true;
                    tab.id = maximizedId;
                    if (chartId) maxchart(chartId);
                } else {
                    maximized = false;
                    tab.id = elementId;
                    if (chartId) minchart(chartId);
                }
            }
        }
        function maximizedreport() {
            toggleMaximize("report_id", "maximizedreport");
        }
        function maximizedyieldchart() {
            toggleMaximize("yield_id", "maximizedyieldchart", "chart1");
        }
        function maximizedplato() {
            toggleMaximize("plato_id", "maximizedplato", "chart2");
        }

    </script>
</body>
</html>
